import { useNavigate, useSearchParams } from 'react-router-dom'
import { NavBar, InfiniteScroll } from 'antd-mobile'
import ArticleItem from '@/pages/Home/ArticleItem'
import styles from './index.module.scss'
import { observer } from 'mobx-react-lite'
import { useStore } from '@/store'
import { useEffect } from 'react'

const Result = () => {
  const navigate = useNavigate()
  const { searchStore } = useStore()
  const [params] = useSearchParams()
  const keyword = params.get('q')

  useEffect(() => {
    // 每次进入时先做一步清理
    searchStore.resetResult()
  }, [])

  const loadMore = async () => {
    console.log('加载了')
    if (keyword) {
      await searchStore.getSearchResult(keyword)
    }
  }
  // 渲染结果列表
  const renderArticleList = () => {
    return searchStore.searchResult.results?.map((item) => {
      return (
        <div
          key={item.art_id}
          className="article-item"
          onClick={() => navigate(`/article?id=${item.art_id}`)}>
          <ArticleItem type={item.cover.type} articleData={item} />
        </div>
      )
    })
  }

  return (
    <div className={styles.root}>
      <NavBar onBack={() => navigate(-1)}>搜索结果</NavBar>
      <div className="article-list">
        {renderArticleList()}
        {/* 加载更多 */}
        {/* 放置的位置很关键 必须在文章变多之后能把它顶到底部 视口外 */}
        {/* 当没有数据的时候一定要及时的把hasMore设置为false 才能停止 否则一直在视口中不断的触发
        上拉加载回调执行 */}
        <InfiniteScroll
          loadMore={loadMore}
          hasMore={searchStore.hasMore}></InfiniteScroll>
      </div>
    </div>
  )
}

export default observer(Result)
